#!/usr/bin/env python
import subprocess,paramiko,os,sys
from moudle.gman import gman
base_dir = os.path.dirname(os.path.dirname(__file__))
sys.path.append(base_dir)

key_file = base_dir + '/config/id_rsa'

def help():
    print('''
   test.ping:  Test the network
       Param:[groupname|ip]
       Eg: solt.py test.ping webs
   test.connect:  Test ssh connect
       Param:[groupname|ip]
       Eg: solt.py test.connect 10.123.1.1
           ''')

def ping(gname):
    ginfo = gman.get_groups()
    try:
        for host in ginfo[gname]:
            re = subprocess.call('ping -c2 ' + host, shell=True,stdout=subprocess.PIPE)
            if re == 0:
                print("Host:{}.ping(\033[31;1mTrue\033[0m)" .format(host))
            else:
                print("Host:{}.ping(\033[31;1mFalse\033[0m)" .format(host))
    except KeyError:
        print("\033[31;1m--No the group!\033[0m")

def connect(gname):
    tf=True
    ginfo = gman.get_groups()
    try:
        for host in ginfo[gname]:
            try:
                test_ssh = paramiko.SSHClient()
                test_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                test_ssh.connect(host, 22, 'root', key_filename=key_file)
            except Exception as e:
                print('Host:{}.connect(\033[31;1mFalse\033[0m)-[{}]'.format(host, e))
                tf=False
            else:
                print('Host:{}.connect(\033[31;1mTrue\033[0m)' .format(host))
    except KeyError:
        print("\033[31;1m--No the group!\033[0m")
    return tf